<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ################

class VMS_VersionManager
{
    public function getCurrentVersion($packageid){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $packageid = (int) $packageid;
        $version = (string) $DB->oneValue($CONFIG->dbprefix.'vms_versions', 'version', "package_id = '{$packageid}' ORDER BY version DESC");
        if(trim($version) == '') $version = '0.0.0';
        return $version;
    }

    public function getCurrentVersionId($packageid){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $packageid = (int) $packageid;
        $version = (int) $DB->oneValue($CONFIG->dbprefix.'vms_versions', 'id', "package_id = '{$packageid}' ORDER BY version DESC");
        return $version;
    }
    
    public function getNextVersion($currentVersion){
        $currentVersion = explode('.', $currentVersion);
        foreach($currentVersion as $k=>$v){};
        $currentVersion[$k]++;
        return ''.implode('.', $currentVersion).'';
    }

    public function isLaterVersion($subjectVersion, $compareVersion){
        $sv = explode('.', $subjectVersion);
        $cv = explode('.', $compareVersion);
        while(count($sv) > count($cv)){
            array_unshift($cv, 0);
        }
        for($i=0; $i<count($sv); $i++){
            if((int) $sv[$i] > (int) $cv[$i]) return true;
        }
        return false;
    }

    public function exportVersion($packageid, $versionid=''){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $vmsObject = JFX::registry('JFX_Module_Vms');

        $packageid = (int) $packageid;
        if($versionid == '') $versionid = $this->getCurrentVersionId($packageid);
        $versionid = (int) $versionid;

        $langs = array();
        $installedLangs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}languages");
        foreach($installedLangs as $k=>$v){
            $langs[] = array(
                'label' => 'package_title',
                'lang' => $v['keyname'],
                'id' => $packageid,
                'value' => $vmsObject->getContentLang('package_title', $packageid, $v['keyname'])
            );
            $langs[] = array(
                'label' => 'change_log',
                'lang' => $v['keyname'],
                'id' => $versionid,
                'value' => $vmsObject->getContentLang('change_log', $versionid, $v['keyname'])
            );
        }

        $pData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_packages WHERE id = '{$packageid}'");
        $vData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_versions WHERE package_id = '{$packageid}' AND id = '{$versionid}'");

        $folders = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}vms_files WHERE package_id = '{$packageid}' AND version_id = '{$versionid}' AND file_type = 0 ORDER BY filename ASC");
        $files = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}vms_files WHERE package_id = '{$packageid}' AND version_id = '{$versionid}' AND file_type = 1 ORDER BY filename ASC");

        foreach($files as $k=>$v){
            if(file_exists($vmsObject->dirname.'/files/'.$v['id'].'.vmsf')){
                $files[$k]['file_contents'] = file_get_contents($vmsObject->dirname.'/files/'.$v['id'].'.vmsf');
            }else{
                $files[$k]['file_contents'] = '';
            }
        }

        $export = array(
            'langs' => $langs,
            'pData' => $pData,
            'vData' => $vData,
            'folders' => $folders,
            'files' => $files
        );

        return serialize($export);
    }

    public function importVersion($import, $newPackageId = '', $newVersionId = ''){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $USER = JFX::registry('JFX_User');
        $vmsObject = JFX::registry('JFX_Module_Vms');

        $import = unserialize($import);
        if(!is_array($import) || 
           !array_key_exists('pData', $import) ||
           !array_key_exists('vData', $import) ||
           !array_key_exists('folders', $import) ||
           !array_key_exists('files', $import) ||
           !array_key_exists('langs', $import)
        ){
            return false;
        }
        // valid import
        $pData = $import['pData'];
        $vData = $import['vData'];
        $files = $import['files'];
        $folders = $import['folders'];
        $langs = $import['langs'];
        
        if($newPackageId == ''){
            // generate new package id
            $packageid = (int) $DB->oneValue($CONFIG->dbprefix.'vms_packages', 'id', "keyname = '{$pData['keyname']}'");
            if($packageid === 0){
                // create new package
                $dbParams = array(
                    'keyname' => $pData['keyname'],
                    'base_path' => $pData['base_path'],
                    'created_tstamp' => time(),
                    'owner_id' => $USER->userid,
                    'current_version' => '0.0.0'
                );
                $newPackageId = $DB->insert($CONFIG->dbprefix.'vms_packages', $dbParams);
            }else{
                $newPackageId = $packageid;
            }
        }
        if($newVersionId == ''){
            // generate new version id
            $version = $this->getCurrentVersion($newPackageId);
            if($DB->countRows($CONFIG->dbprefix.'vms_versions', "package_id = '{$newPackageId}' AND version = '{$vData['version']}'")==0){
                // create new version
                $dbParams = $vData;
                unset($dbParams['id']);
                $dbParams['package_id'] = $newPackageId;
                $newVersionId = $DB->insert($CONFIG->dbprefix.'vms_versions', $dbParams);
            }else{
                // get the version id
                $newVersionId = $DB->oneValue($CONFIG->dbprefix.'vms_versions', 'id', "package_id = '{$newPackageId}' AND version = '{$vData['version']}'");
            }
        }

        // delete existing files and folders in this version
        $DB->delete($CONFIG->dbprefix.'vms_files', "package_id = '{$newPackageId}' AND version_id = '{$newVersionId}'");

        // create files and folders
        foreach($files as $k=>$v){
            unset($v['id']);
            $fileContent = $v['file_contents'];
            unset($v['file_contents']);
            $v['package_id'] = $newPackageId;
            $v['version_id'] = $newVersionId;
            $fileid = $DB->insert($CONFIG->dbprefix.'vms_files', $v);
            if(file_exists($vmsObject->dirname.'/files/'.$fileid.'.vmsf')) unlink($vmsObject->dirname.'/files/'.$fileid.'.vmsf');
            $fh = fopen($vmsObject->dirname.'/files/'.$fileid.'.vmsf', 'w');
            fwrite($fh, $fileContent);
            fclose($fh);
        }
        foreach($folders as $k=>$v){
            unset($v['id']);
            unset($v['file_contents']);
            $v['package_id'] = $newPackageId;
            $v['version_id'] = $newVersionId;
            $DB->insert($CONFIG->dbprefix.'vms_files', $v);
        }

        // do languages
        $installedLangs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}languages");
        foreach($installedLangs as $k=>$v){
            foreach($langs as $key=>$value){
                if($value['lang']===$v['keyname']){
                    $vmsObject->updateContentLang($value['label'], $newPackageId, $value['value'], $v['keyname'], '*');
                }
            }
        }

        // success!
        return true;

    }// end import fundtion


    

}// end class